package com.zdpx.pxframework.log.util;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.zdpx.pxframework.core.context.SecurityContextHolder;
import com.zdpx.pxframework.core.pojo.LoginUser;
import com.zdpx.pxframework.core.util.IpUtil;
import com.zdpx.pxframework.core.vo.CodeMsg;
import com.zdpx.pxframework.core.vo.Result;
import com.zdpx.pxframework.log.annotations.OperateLog;
import com.zdpx.pxframework.log.dto.OperateLogModelDto;
import com.zdpx.pxframework.log.enums.LogTypeEnum;
import com.zdpx.pxframework.log.enums.OperateTypeEnum;
import eu.bitwalker.useragentutils.UserAgent;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.IntStream;

/**
 * 日志工具类
 *
 * @Description:
 * @Author: Cheng XiaoXiao
 * @Date: 2022/5/25 9:29
 */
public class LogUtil {

    /**
     * 生成日志对象信息
     *
     * @param joinPoint    切入点
     * @param operateLog   日志注解
     * @param apiOperation sqagger注解
     * @param startTime    开始时间
     * @param result       结果信息
     * @param exception    异常信息
     * @return 日志信息
     */
    public static OperateLogModelDto getOperateLogModelDto(ProceedingJoinPoint joinPoint, OperateLog operateLog, ApiOperation apiOperation, Date startTime, Object result, Throwable exception) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String header = request.getHeader("user-agent");

        OperateLogModelDto operateLogModelDto = new OperateLogModelDto();

        //填充请求相关字段
        fillRequestFields(request, operateLogModelDto);

        //填充模块相关字段
        fillModuleFields(operateLogModelDto, joinPoint, operateLog, apiOperation);

        //用户信息的处理
        LoginUser loginUser = SecurityContextHolder.getUser();
        if (loginUser != null) {
            operateLogModelDto.setCreateBy(loginUser.getUserName());
        }

        operateLogModelDto.setApiStatus(LogTypeEnum.NORMAL.getType());

        //填充UserAgent相关字段
        fillUserAgentFields(startTime, request, header, operateLogModelDto);

        //填充method相关参数
        fillMethodResultFields(joinPoint, operateLog, result, exception, operateLogModelDto);
        return operateLogModelDto;
    }

    /**
     * 填充请求相关信息
     *
     * @param request            请求
     * @param operateLogModelDto 日志实体对象
     */
    private static void fillRequestFields(HttpServletRequest request, OperateLogModelDto operateLogModelDto) {
        operateLogModelDto.setRequestUri(URLUtil.getPath(request.getRequestURI()));
        operateLogModelDto.setRequestArgs(HttpUtil.toParams(request.getParameterMap()));
        operateLogModelDto.setRequestMethod(request.getMethod());
    }

    /**
     * 填充模块对应相关信息
     *
     * @param operateLogDTO 日志对象
     * @param joinPoint     切入点
     * @param operateLog    操作日志注解
     * @param apiOperation  swagger注解
     */
    private static void fillModuleFields(OperateLogModelDto operateLogDTO,
                                         ProceedingJoinPoint joinPoint,
                                         OperateLog operateLog,
                                         ApiOperation apiOperation) {
        // 1. 获取操作日志设置的对应模块名称
        if (operateLog != null) {
            operateLogDTO.setModuleName(operateLog.module());
        }
        if (StrUtil.isEmpty(operateLogDTO.getModuleName())) {
            Class<?>[] interfaces = ((MethodSignature) joinPoint.getSignature()).getMethod().getDeclaringClass().getInterfaces();
            if (interfaces.length > 0) {
                Api api = interfaces[0].getAnnotation(Api.class);
                if (api != null) {
                    // 1. 没有的话，读取 Swagger中的 @API 的 tags 属性
                    if (StrUtil.isEmpty(operateLogDTO.getModuleName()) && ArrayUtil.isNotEmpty(api.tags())) {
                        operateLogDTO.setModuleName(api.tags()[0]);
                    }
                }
            }
        }

        // 2. 接口描述属性信息
        if (operateLog != null) {
            operateLogDTO.setTitle(operateLog.name());
        }
        if (StrUtil.isEmpty(operateLogDTO.getTitle()) && apiOperation != null) {
            // 2. 没有的话，读取 Swagger中的 @ApiOperation 的 value 属性
            operateLogDTO.setTitle(apiOperation.value());
        }

        // 3. 操作类型
        if (operateLog != null && ArrayUtil.isNotEmpty(operateLog.type())) {
            operateLogDTO.setOperateType(operateLog.type().getType());
        }
        if (operateLogDTO.getOperateType() == null) {
            RequestMethod requestMethod = obtainFirstMatchRequestMethod(obtainRequestMethod(joinPoint));
            OperateTypeEnum operateLogType = convertOperateLogType(requestMethod);
            operateLogDTO.setOperateType(operateLogType != null ? operateLogType.getType() : null);
        }
    }

    /**
     * 根据请求方式集合，获取最优的请求方式
     *
     * @param requestMethods 请求集合
     * @return 最优的请求方式
     */
    private static RequestMethod obtainFirstMatchRequestMethod(RequestMethod[] requestMethods) {
        if (ArrayUtil.isEmpty(requestMethods)) {
            return null;
        }
        // 优先，匹配最优的 POST、PUT、DELETE
        RequestMethod result = obtainFirstLogRequestMethod(requestMethods);
        if (result != null) {
            return result;
        }
        // 然后，匹配次优的 GET
        result = Arrays.stream(requestMethods).filter(requestMethod -> requestMethod == RequestMethod.GET)
                .findFirst().orElse(null);
        if (result != null) {
            return result;
        }
        // 兜底，获得第一个
        return requestMethods[0];
    }

    /**
     * 根据请求方式转换为操作日志的类型
     *
     * @param requestMethod 请求方式
     * @return 操作日志类型
     */
    private static OperateTypeEnum convertOperateLogType(RequestMethod requestMethod) {
        if (requestMethod == null) {
            return null;
        }
        switch (requestMethod) {
            case GET:
                return OperateTypeEnum.GET;
            case POST:
                return OperateTypeEnum.CREATE;
            case PUT:
                return OperateTypeEnum.UPDATE;
            case DELETE:
                return OperateTypeEnum.DELETE;
            default:
                return OperateTypeEnum.OTHER;
        }
    }


    /**
     * 填充 UserAgent相关信息
     *
     * @param startTime          开始时间
     * @param request            请求
     * @param header             请求头
     * @param operateLogModelDto 操作日志对象
     */
    private static void fillUserAgentFields(Date startTime, HttpServletRequest request, String header, OperateLogModelDto operateLogModelDto) {
        UserAgent userAgent = UserAgent.parseUserAgentString(header);
        operateLogModelDto.setUserAgent(header);
        operateLogModelDto.setBrowser(userAgent.getBrowser().toString());
        operateLogModelDto.setOperateSystem(userAgent.getOperatingSystem().toString());
        operateLogModelDto.setCreateTime(startTime);
        operateLogModelDto.setIp(IpUtil.getIpAddr(request));
        operateLogModelDto.setUseTime(System.currentTimeMillis() - startTime.getTime());
    }


    /**
     * 填充method及返回值相关信息
     *
     * @param joinPoint          切入点
     * @param operateLog         日志注解
     * @param result             结果
     * @param exception          异常
     * @param operateLogModelDto 日志实体对象
     */
    private static void fillMethodResultFields(ProceedingJoinPoint joinPoint, OperateLog operateLog, Object result, Throwable exception, OperateLogModelDto operateLogModelDto) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        operateLogModelDto.setJavaMethod(methodSignature.toString());
        if (operateLog == null || operateLog.logArgs()) {
            operateLogModelDto.setJavaMethodArgs(obtainMethodArgs(joinPoint));
        }
        if (operateLog == null || operateLog.logResultData()) {
            operateLogModelDto.setResultData(obtainResultData(result));
        }
        // （正常）处理 resultCode 和 resultMsg 字段
        if (result != null) {
            if (result instanceof Result) {
                Result<?> commonResult = (Result<?>) result;
                operateLogModelDto.setResultCode(commonResult.getCode());
                operateLogModelDto.setResultMsg(commonResult.getMsg());
            }
        }
        // （异常）处理 resultCode 和 resultMsg 字段
        if (exception != null) {
            operateLogModelDto.setResultCode(CodeMsg.ERROR.getCode());
            operateLogModelDto.setResultMsg(ExceptionUtil.getRootCauseMessage(exception));
        }
    }


    /**
     * 对结果数据进行处理，如果为 Result 时，只取里面的数据信息
     *
     * @param result 原始返回结果
     * @return 处理之后的结果信息
     */
    private static String obtainResultData(Object result) {
        if (result instanceof Result) {
            result = ((Result<?>) result).getData();
        }
        return JSON.toJSONString(result);
    }


    /**
     * 获取切入点所对应方法的参数值
     *
     * @param joinPoint 切入点
     * @return 参数信息
     */
    private static String obtainMethodArgs(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] argNames = methodSignature.getParameterNames();
        Object[] argValues = joinPoint.getArgs();
        // 拼接参数
        Map<String, Object> args = new HashMap<>(argValues.length);
        for (int i = 0; i < argNames.length; i++) {
            String argName = argNames[i];
            Object argValue = argValues[i];
            args.put(argName, isIgnoreArgs(argValue) ? "[ignore]" : argValue);
        }
        return JSON.toJSONString(args);
    }


    /**
     * 是否忽略某些参数的处理
     *
     * @param object 参数值
     * @return 是否忽略
     */
    public static boolean isIgnoreArgs(Object object) {
        Class<?> clazz = object.getClass();
        // 处理数组的情况
        if (clazz.isArray()) {
            return IntStream.range(0, Array.getLength(object))
                    .anyMatch(index -> isIgnoreArgs(Array.get(object, index)));
        }
        // 递归，处理数组、Collection、Map 的情况
        if (Collection.class.isAssignableFrom(clazz)) {
            return ((Collection<?>) object).stream()
                    .anyMatch(LogUtil::isIgnoreArgs);
        }
        if (Map.class.isAssignableFrom(clazz)) {
            return isIgnoreArgs(((Map<?, ?>) object).values());
        }
        // obj
        return object instanceof MultipartFile
                || object instanceof HttpServletRequest
                || object instanceof HttpServletResponse
                || object instanceof BindingResult;
    }


    /**
     * 根据切入点获取请求的method
     *
     * @param joinPoint 切入点
     * @return 请求method列表
     */
    public static RequestMethod[] obtainRequestMethod(ProceedingJoinPoint joinPoint) {
        RequestMapping requestMapping = AnnotationUtils.getAnnotation(
                ((MethodSignature) joinPoint.getSignature()).getMethod(), RequestMapping.class);
        return requestMapping != null ? requestMapping.method() : new RequestMethod[]{};
    }

    /**
     * 判断method中是否存在非GET请求
     *
     * @param requestMethods 请求方式集合
     * @return 匹配的第一个非GET请求方式
     */
    public static RequestMethod obtainFirstLogRequestMethod(RequestMethod[] requestMethods) {
        if (ArrayUtil.isEmpty(requestMethods)) {
            return null;
        }
        return Arrays.stream(requestMethods).filter(requestMethod ->
                        requestMethod == RequestMethod.POST
                                || requestMethod == RequestMethod.PUT
                                || requestMethod == RequestMethod.DELETE)
                .findFirst().orElse(null);
    }
}
